package org.example.groupwarehouse.service;

import org.example.groupwarehouse.entity.Users;
import org.example.groupwarehouse.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 用户服务类
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MinioService minioService;

    // 手机号验证正则表达式：11位数字且以1开头
    private static final Pattern PHONE_PATTERN = Pattern.compile("^1\\d{10}$");
    // 邮箱验证正则表达式
    private static final Pattern EMAIL_PATTERN = Pattern.compile("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$");
    // 密码验证正则表达式：以大写字母开头，只能包含字母和数字，长度6-10位
    private static final Pattern PASSWORD_PATTERN = Pattern.compile("^[A-Z][A-Za-z0-9]{5,9}$");

    public List<Users> getAllUsers() {
        return userMapper.getAllUsers();
    }

    /* 用户相关操作*/
    public void freeze(Integer id) {
        userMapper.updateUserStatus(id,"2");
    }
    public void unfreeze(Integer id) {
        userMapper.updateUserStatus(id,"0");
    }
    public void blacklist(Integer id) {
        userMapper.updateUserStatus(id,"3");
    }
    public void unblacklist(Integer id) {
        userMapper.updateUserStatus(id,"0");
    }
    public void delete(Integer id) {
        Integer  n  = userMapper.updateUserStatus(id,"4");

        System.out.println("n ------------- > " + n);
    }

    private int updateUserStatus(Integer id, String status) {
        return userMapper.updateUserStatus(id, status);
    }

    /**
     * 根据账号获取用户信息
     */
    public Users getUserByAccount(String account) {
        return userMapper.selectByAccount(account);
    }
    
    /**
     * 注册新用户
     */
    public boolean insertUser(String account, String password, String email, String
            telphone, String avatarUrl) {

        Users cur = userMapper.selectByAccount(account);
        if(cur != null){
            //已经被注册
            return false;
        }
        
        // 验证密码格式
        if (!PASSWORD_PATTERN.matcher(password).matches()) {
            return false;
        }
        
        //    1.构建新的用户实体对象
        Users user = new Users();
        user.setAccount(account);
        //密码是md5加密,把加密的字符串进行填充,springboot自带md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        user.setEmail(email);
        user.setTelphone(telphone);
        //设置初始数据
        user.setPoints(0);
        user.setMoney(BigDecimal.valueOf(0.0));
        user.setRegTime(LocalDateTime.now());
        user.setStatus("1");
        //设置头像URL
        user.setAvatar(avatarUrl != null ? avatarUrl : "");
        //注册
        int re = userMapper.insertUser(user);
        return re > 0;
    }
    /**
     * 用户登录
     */
    public Users login(String account, String password) {
        Users user = userMapper.selectByAccount(account);
        if(user==null){
            return null;//没有该用户
        }
        if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return null; // 密码错误
        }
        if ("2".equals(user.getStatus()) || "3".equals(user.getStatus())) {
            return null; // 用户被冻结或在黑名单中
        }
        user.setLastLoginTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
        user.setStatus("1"); // 更新状态为正常
        userMapper.updateUser(user);
        //将密码转为md5加密字段
        if(user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))){
            return user;
        }else{
            return null;//登录失败
        }
    }

    /**
     * 上传用户头像
     */
    public String uplaodAvatar(MultipartFile file) throws Exception {
        //调用minio的方法来保存文件
        return minioService.uploadFile(file);
    }
    
    /**
     * 更新用户个人信息
     */
    public boolean updateUserProfile(Users user) {
        // 验证手机号格式
        if (!PHONE_PATTERN.matcher(user.getTelphone()).matches()) {
            return false;
        }
        
        // 验证邮箱格式
        if (!EMAIL_PATTERN.matcher(user.getEmail()).matches()) {
            return false;
        }
        
        return userMapper.updateUserProfile(user) > 0;
    }
    
    /**
     * 验证原密码并更新为新密码
     */
    public boolean updatePassword(String account, String oldPassword, String newPassword) {
        // 验证新密码格式
        if (!PASSWORD_PATTERN.matcher(newPassword).matches()) {
            return false;
        }
        
        // 验证原密码是否正确
        Users user = userMapper.selectByAccount(account);
        if (user == null) {
            return false;
        }
        
        // 验证原密码
        String oldPasswordMd5 = DigestUtils.md5DigestAsHex(oldPassword.getBytes());
        if (!user.getPassword().equals(oldPasswordMd5)) {
            return false;
        }
        
        // 更新为新密码（MD5加密）
        String newPasswordMd5 = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        return userMapper.updatePassword(account, newPasswordMd5) > 0;
    }

} 